package me.zhengjie.modules.hanzi.service;

import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.hanzi.domain.GameData;
import me.zhengjie.modules.hanzi.domain.HanziCharacter;
import me.zhengjie.modules.hanzi.mapper.CharacterMapper;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
@RequiredArgsConstructor
public class GameService {
    private final CharacterMapper characterMapper;
    
    public GameData getGameData(String gameType, Integer level) {
        GameData gameData = new GameData();
        
        // 根据游戏类型和难度等级获取汉字
        List<HanziCharacter> characters;
        if ("match".equals(gameType)) {
            characters = characterMapper.selectList(
                new QueryWrapper<HanziCharacter>()
                    .eq(level != null, "level", level)
                    .orderByAsc("RAND()")
                    .last("LIMIT 4")
            );
        } else {
            throw new IllegalArgumentException("不支持的游戏类型: " + gameType);
        }
        
        // 构建左右两边的数据
        List<GameData.GameItem> left = new ArrayList<>();
        List<GameData.GameItem> right = new ArrayList<>();
        
        for (HanziCharacter character : characters) {
            // 左边显示汉字和拼音
            GameData.GameItem leftItem = new GameData.GameItem();
            leftItem.setCharacter(character.getCharacter());
            leftItem.setPinyin(character.getPinyin());
            leftItem.setMatched(false);
            left.add(leftItem);
            
            // 右边只显示拼音
            GameData.GameItem rightItem = new GameData.GameItem();
            rightItem.setPinyin(character.getPinyin());
            rightItem.setMatched(false);
            right.add(rightItem);
        }
        
        // 打乱右侧拼音顺序
        Collections.shuffle(right);
        
        gameData.setLeft(left);
        gameData.setRight(right);
        return gameData;
    }
} 